//
//  PywCommonApiManager.m
//  PywCommonSDKDemo
//
//  Created by Ampaw on 2017/8/14.
//  Copyright © 2017年 Ampaw. All rights reserved.
//

#import "PywCommonApiManager.h"
#import "PywCommonRequestApi.h"
#import "PywCommonPlatformInfo.h"
#import "PywCommonSDKParameter.h"
#import "PywCommonMutableDictionary.h"

@interface PywCommonApiManager ()<UIAlertViewDelegate>
@property (nonatomic, strong) id target;
@property (nonatomic, copy) NSString *updateUrlString; // 强更游戏地址
@end

@implementation PywCommonApiManager

NSString *const CommonSDK_Gamekey       = @"gamekey";           // 游戏参数Key
NSString *const CommonSDK_Tid           = @"tid";               // 请求流水号
NSString *const CommonSDK_ChannelID     = @"channel_id";        // 渠道编号

NSString *const CommonSDK_GameId        = @"gameid";            // 游戏ID
NSString *const CommonSDK_ChannelUid    = @"channel_uid";       // 渠道登录完成后的用户id
NSString *const CommonSDK_ChannelToken  = @"channel_token";     // 渠道登录完成后的token

NSString *const CommonSDK_CpUid         = @"cp_uid";            // 朋友玩用户ID
NSString *const CommonSDK_Account       = @"account";           // 新建的朋友玩游戏账号

NSString *const CommonSDK_ChargeType    = @"charge_type";       // 充值类型，1为定额充值，0为任意充值
NSString *const CommonSDK_CpProductId   = @"cp_product_id";     // 产品ID，任意支付的时候，可不传
NSString *const CommonSDK_OrderPrice    = @"order_price";       // 订单价格
NSString *const CommonSDK_CpOrderSn     = @"cp_order_sn";       // 游戏订单号
NSString *const CommonSDK_CpOrderInfo   = @"cp_order_info";     // 订单额外信息，JSON字符串（如：区服、角色名）
NSString *const CommonSDK_RoleName      = @"rolename";          // 角色名称
NSString *const CommonSDK_RoleID        = @"roleid";            // 角色ID
NSString *const CommonSDK_ServiceID     = @"serverArea";        // 区服ID
NSString *const CommonSDK_Service       = @"service";           // 区服名称

static id manager = nil;
+ (PywCommonApiManager *)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PywCommonApiManager alloc] init];
    });
    return manager;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void) api_InitWithGamekey:(NSString *)gamekey
                     target:(id)target
                    success:(CommonSDKRequestSuccess)success
{
    self.target  = target;
    self.success = success;
    
    NSString *sub_gamekey = [PywCommonPlatformInfo sharedCommonPlatformInfo].subGamekey;
    if (sub_gamekey.length == 0) { // 当配置文件中，没有子渠道gameKey时，是母包
        
        [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey = gamekey;
    }else{
        
        [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey = sub_gamekey;
    }
    
    // 包装请求聚合Init参数
    PywCommonMutableDictionary *params = [PywCommonMutableDictionary dictionary];
    NSString *tid = [PywCommonPlatformInfo sharedCommonPlatformInfo].tid;
    NSString *channel_id = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_id;
    NSString *game_key = [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey;
    [params setObject:game_key forKey:CommonSDK_Gamekey];
    [params setObject:tid forKey:CommonSDK_Tid];
    [params setObject:channel_id forKey:CommonSDK_ChannelID];
    COMLog(@"聚合init请求参数：Params = %@",params.description);
    
    // 发起请求
    [PywCommonRequestApi requestInitWithParams:params Completion:^(NSDictionary *dict) {
        NSInteger code = [[dict objectForKey:@"ack"] integerValue];
        if (code == 200) {
            COMLog(@"聚合初始化成功，返回数据：Dict = %@",dict.description);
            // 检查更新
            [self checkVersionUpdateWithDict:dict];
            
        }else{
            [PywCommonPlatformInfo sharedCommonPlatformInfo].isInitSuccess = false;
            NSString *msg = [dict objectForKey:@"msg"];
            COMLog(@"******** 请求失败 code = %ld ********",(long)code);
            [PywCommonMBProgressHUD showError:msg];
            
            // 发送回调
            NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_InitState_Faliure] forKey:@"result"];
            [mDict setObject:@"初始化失败！" forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_InitNotification
                                                                object:nil
                                                              userInfo:mDict];
        }
    }];
}

- (void)api_Login
{
    // 请求聚合Login参数
    PywCommonMutableDictionary *params = [PywCommonMutableDictionary dictionary];
    NSString *gamekey = [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey;
    NSString *gameid = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameid;
    NSString *tid = [PywCommonPlatformInfo sharedCommonPlatformInfo].tid;
    NSString *channel_id = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_id;
    NSString *channel_uid = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_uid;
    NSString *channel_token = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_token;
    [params setObject:gamekey forKey:CommonSDK_Gamekey];
    [params setObject:gameid forKey:CommonSDK_GameId];
    [params setObject:tid forKey:CommonSDK_Tid];
    [params setObject:channel_id forKey:CommonSDK_ChannelID];
    [params setObject:channel_uid forKey:CommonSDK_ChannelUid];
    [params setObject:channel_token forKey:CommonSDK_ChannelToken];
    COMLog(@"params = %@",params.description);
    
    // 发起请求
    [PywCommonRequestApi requestLoginWithParams:params Completion:^(NSDictionary *dict) {
        NSDictionary *data = [dict objectForKey:@"data"];
        NSInteger code = [[dict objectForKey:@"ack"] integerValue];
        if (code == 200) {
            COMLog(@"聚合登录成功，返回数据：Dict = %@",dict.description);
            // 存储数据
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_account = [data objectForKey:@"account"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_cp_uid = [data objectForKey:@"cp_uid"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_token = [data objectForKey:@"token"];
            NSString *ch_uid = [data objectForKey:@"channel_uid"];
            if(ch_uid){
                //如果服务端返传了chnanel_uid,则使用服务端返传的值
                [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_uid = [data objectForKey:@"channel_uid"];
            }
            
            // 发送回调
            PywCommonMutableDictionary *mDict = [PywCommonMutableDictionary dictionary];
            NSString *user_id = [data objectForKey:@"cp_uid"];
            NSString *user_token = [data objectForKey:@"token"];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_LoginState_Success] forKey:@"result"];
            [mDict setObject:@"登录成功！" forKey:@"info"];
            [mDict setObject:user_id forKey:@"userid"];
            [mDict setObject:user_token forKey:@"token"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_LoginNotification
                                                                object:nil
                                                              userInfo:mDict];
        }else{
            NSString *msg = [dict objectForKey:@"msg"];
            COMLog(@"******** 请求失败 code = %ld ********",(long)code);
            [PywCommonMBProgressHUD showError:msg];
            
            // 发送回调
            NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_LoginState_Faliure] forKey:@"result"];
            [mDict setObject:@"登录失败！" forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_LoginNotification
                                                                object:nil
                                                              userInfo:mDict];
        }
    }];
}

- (void)api_UploadRoleInfo:(NSDictionary *)roleInfo
{
    // 请求参数
    PywCommonMutableDictionary *params = [PywCommonMutableDictionary dictionary];
    NSString *tid = [PywCommonPlatformInfo sharedCommonPlatformInfo].tid;
    NSString *gamekey = [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey;
    NSString *gameid = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameid;
    NSString *channel_id = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_id;
    NSString *account = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_account;
    
    // 区服名称
    NSString *serverAreaName = [roleInfo objectForKey:keyCom_GameServiceName];
    // 区服ID
    NSString *serverArea = [roleInfo objectForKey:keyCom_GameServiceId];
    // 角色ID
    NSString *roleid = [roleInfo objectForKey:keyCom_GameRoleId];
    // 角色名称
    NSString *roleName = [roleInfo objectForKey:keyCom_GameRoleName];
    // 角色等级
    NSString *roleLevel = [roleInfo objectForKey:keyCom_GameRoleLevel];
    
    [params setObject:gamekey forKey:CommonSDK_Gamekey];
    [params setObject:tid forKey:CommonSDK_Tid];
    [params setObject:channel_id forKey:CommonSDK_ChannelID];
    [params setObject:account forKey:CommonSDK_Account];
    [params setObject:gameid forKey:@"game_id"];
    [params setObject:serverAreaName forKey:@"serverAreaName"];
    [params setObject:serverArea forKey:@"serverArea"];
    [params setObject:roleid forKey:@"roleid"];
    [params setObject:roleName forKey:@"roleName"];
    [params setObject:roleLevel forKey:@"roleLevel"];
    COMLog(@"params = %@",params.description);
    
    [PywCommonRequestApi requestUploadRoleInfoWithParams:params Completion:^(NSDictionary *dict) {
        //        NSDictionary *data = [dict objectForKey:@"data"];
        NSInteger code = [[dict objectForKey:@"ack"] integerValue];
        if (code == 200) {
            COMLog(@"游戏角色信息，同步成功！");
        }else{
            COMLog(@"游戏角色信息，同步失败！");
        }
    }];
}

- (void)api_CreateOrdertwithPayInfo:(NSDictionary *)payInfo
                             target:(id)target
                            success:(CommonSDKRequestSuccess)success
{
    self.target  = target;
//    self.success = success;
    
    // 包装请求参数
    PywCommonMutableDictionary *params = [PywCommonMutableDictionary dictionary];
    NSString *gameID        = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameid;
    NSString *gameKey       = [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey;
    NSString *tid           = [PywCommonPlatformInfo sharedCommonPlatformInfo].tid;
    NSString *channelID     = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_id;
    NSString *channelUid    = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_uid;
    NSString *cpUid         = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_cp_uid;
    NSString *account       = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_account;
    
    NSString *chargeType    = [payInfo objectForKey:keyCom_PayType];
    NSString *cp_product_id = [payInfo objectForKey:keyCom_GoodsId];
    NSString *order_price   = [payInfo objectForKey:keyCom_GoodsPrice];
    NSString *cp_order_sn   = [payInfo objectForKey:keyCom_GameOrderId];
    NSString *roleid        = [[payInfo objectForKey:keyCom_GameRoleInfo] objectForKey:keyCom_GameRoleId];
    NSString *roleName      = [[payInfo objectForKey:keyCom_GameRoleInfo] objectForKey:keyCom_GameRoleName];
    NSString *serviceid     = [[payInfo objectForKey:keyCom_GameRoleInfo] objectForKey:keyCom_GameServiceId];
    NSString *service       = [[payInfo objectForKey:keyCom_GameRoleInfo] objectForKey:keyCom_GameServiceName];
    NSString *cp_order_info = [self convertToJsonData:[payInfo objectForKey:keyCom_CustomParams]];
  
    [params setObject:gameID forKey:CommonSDK_GameId];
    [params setObject:gameKey forKey:CommonSDK_Gamekey];
    [params setObject:tid forKey:CommonSDK_Tid];
    [params setObject:channelID forKey:CommonSDK_ChannelID];
    [params setObject:channelUid forKey:CommonSDK_ChannelUid];
    [params setObject:account forKey:CommonSDK_Account];
    [params setObject:cpUid forKey:CommonSDK_CpUid];
    [params setObject:cp_product_id forKey:CommonSDK_CpProductId];
    [params setObject:chargeType forKey:CommonSDK_ChargeType];
    [params setObject:order_price forKey:CommonSDK_OrderPrice];
    [params setObject:cp_order_sn forKey:CommonSDK_CpOrderSn];
    [params setObject:cp_order_info forKey:CommonSDK_CpOrderInfo];
    [params setObject:roleid forKey:CommonSDK_RoleID];
    [params setObject:roleName forKey:CommonSDK_RoleName];
    [params setObject:serviceid forKey:CommonSDK_ServiceID];
    [params setObject:service forKey:CommonSDK_Service];
    COMLog(@"params = %@",params.description);
    
    // 发起请求
    [PywCommonRequestApi requestCreatOrderWithParams:params Completion:^(NSDictionary *dict) {
        NSDictionary *data = [dict objectForKey:@"data"];
        NSInteger code = [[dict objectForKey:@"ack"] integerValue];
        if (code == 200) {
            COMLog(@"聚合下单成功，返回数据：Dict = %@",dict.description);
            //存储订单返回数据
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_channel_order_info = [data valueForKey:@"channel_order_info"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_channel_order_sn = [data valueForKey:@"channel_order_sn"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_channel_prod_id = [data valueForKey:@"channel_prod_id"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].common_channel_order_price = [data valueForKey:@"order_price"];
            [PywCommonPlatformInfo sharedCommonPlatformInfo].rate = [data objectForKey:@"rate"];
            
            NSInteger change_pkg = [[data objectForKey:@"channel_id"] integerValue];
            BOOL use_third_channel = [[data objectForKey:@"use_third_channel"] boolValue];
            // 回调请求数据
            if (success) {
                 success(change_pkg,use_third_channel,nil,self.target);
            }
           
        }else{
            NSString *msg = [dict objectForKey:@"msg"];
            COMLog(@"******** 请求失败 code = %ld ********",(long)code);
            [PywCommonMBProgressHUD showError:msg];
            
            // 发送回调
            NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_PayState_Finish] forKey:@"result"];
            [mDict setObject:@"支付完成！" forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_PayNotification
                                                                object:nil
                                                              userInfo:mDict];
        }

    }];
}

- (void)api_Pay
{
    PywCommonMutableDictionary *params = [PywCommonMutableDictionary dictionary];
    NSString *tid = [PywCommonPlatformInfo sharedCommonPlatformInfo].tid;
    NSString *gameid = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameid;
    NSString *gamekey = [PywCommonPlatformInfo sharedCommonPlatformInfo].gamekey;
    NSString *channel_id = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_id;
    NSString *channel_uid = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_uid;
    NSString *account = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_account;
    NSString *common_cp_uid = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_cp_uid;
    NSString *common_channel_order_sn = [PywCommonPlatformInfo sharedCommonPlatformInfo].common_channel_order_sn;
    
    [params setObject:tid forKey:CommonSDK_Tid];
    [params setObject:gameid forKey:CommonSDK_GameId];
    [params setObject:gamekey  forKey:CommonSDK_Gamekey];
    [params setObject:channel_id forKey:CommonSDK_ChannelID];
    [params setObject:channel_uid forKey:CommonSDK_ChannelUid];
    [params setObject:account forKey:CommonSDK_Account];
    [params setObject:common_cp_uid forKey:CommonSDK_CpUid];
    [params setObject:common_channel_order_sn forKey:@"channel_order_sn"];
    [PywCommonRequestApi requestStartPayWithParams:params Completion:^(NSDictionary *dict) {
        NSInteger code = [[dict objectForKey:@"ack"] integerValue];
        if (code == 200) {
            COMLog(@"聚合支付成功，返回数据：Dict = %@",dict.description);
            // 发送回调
            NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_PayState_Finish] forKey:@"result"];
            [mDict setObject:@"支付完成！" forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_PayNotification
                                                                object:nil
                                                              userInfo:mDict];
        }else{
            // 发送回调
            NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
            [mDict setObject:[NSNumber numberWithInt:CommonSDK_PayState_Finish] forKey:@"result"];
            [mDict setObject:@"支付完成！" forKey:@"info"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCP_XpCommon_PayNotification
                                                                object:nil
                                                              userInfo:mDict];
            COMLog(@"******** 请求失败 code = %ld ********",(long)code);
        }
    }];
}

#pragma mark - 字典 与 json 转换
/// 字典转json字符串方法
-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        COMLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
/// json字符串转字典方法
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        COMLog(@"json解析失败：%@",err);
        return nil;
    }
    return dict;
}


#pragma mark - Check version update
- (void)checkVersionUpdateWithDict:(NSDictionary *)dict
{
    NSDictionary *data = [dict objectForKey:@"data"];
    
    self.updateUrlString = [data objectForKey:@"setup_file"];
    if (self.updateUrlString.length > 0) { // 强更app应用
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"发现新版本，需更新版本。"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
        [alertView show];
    }else{
        
        [PywCommonPlatformInfo sharedCommonPlatformInfo].isInitSuccess = true;
        // 存储数据
        [PywCommonPlatformInfo sharedCommonPlatformInfo].apisecret = [data objectForKey:@"apisecret"];
        [PywCommonPlatformInfo sharedCommonPlatformInfo].gameid = [data objectForKey:@"gameid"];
        
        // 处理第三方渠道参数,将返回的JSON字符串转换为字典
        NSString *third_channel_param = [data objectForKey:@"third_channel_param"];
        NSDictionary *thirdChannelParams = [self dictionaryWithJsonString:third_channel_param];
        
        NSInteger change_pkg = [[data objectForKey:@"channel_id"] integerValue];
        BOOL use_third_channel = [[data objectForKey:@"use_third_channel"] boolValue];
        // 回调请求数据
        if (self.success) {
            self.success(change_pkg,use_third_channel,thirdChannelParams,self.target);
        }
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.updateUrlString]];
    // 退出应用
    COMLog(@"跳转更新，并退出应用！");
    exit(0);
}

@end
